import network
import usocket as socket  # 在 MicroPython 中使用 usocket
import utime
from machine import I2C, Pin, ADC, SPI
import icm20948
import st7789
from joystickshield import JoystickShield

# 初始化 I2C 接口和摇杆/按键
i2c = I2C(0)
imu = icm20948.ICM20948(i2c, accel_scale=icm20948.GPM_8)
pinA = Pin(14, Pin.IN)
pinB = Pin(0, Pin.IN)
pinC = Pin(1, Pin.IN)
pinD = Pin(2, Pin.IN)
adcX = ADC(Pin(12))
adcY = ADC(Pin(13))
joystick = JoystickShield(pinA, pinB, pinC, pinD, adcX, adcY)

# 初始化屏幕
spi = SPI(0, baudrate=40000000, polarity=1, phase=0, bits=8, endia=0, sck=Pin(6), mosi=Pin(8))
display = st7789.ST7789(spi, 240, 240, reset=Pin(11, func=Pin.GPIO, dir=Pin.OUT), dc=Pin(7, func=Pin.GPIO, dir=Pin.OUT))
display.init()
display.fill(st7789.BLACK)

# 定义加速度阈值
threshold = 500

# 连接到 Wi-Fi 网络
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('abc123', 'fh205219', security=network.AUTH_PSK)
print(wlan.config())

server_ip = '192.168.248.101'
server_port = 5000

last_character_command = ""  # 记录上一次发送的角色指令
mouse_left_down = False
mode_switch_pending = False  # 模式切换标志
current_mode = "water"

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(5)  # 设置超时时间为 5 秒
    s.connect((server_ip, server_port))
    print('与电脑的连接成功')

    try:
        while True:
            commands = []
            # display.fill(st7789.BLACK)
            # 显示当前模式
            if current_mode == "water":
                display.draw_string(0, 0, "character:water", color=st7789.BLUE, bg=st7789.BLACK, size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
            else:
                display.draw_string(0, 0, "character: fire", color=st7789.RED, bg=st7789.BLACK, size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)

            # 读取姿态传感器数据
            if imu.dataupdate() and imu.dataready():
                acc_x = imu.acc_x()
                acc_y = imu.acc_y()

                character_command = ""
                if acc_x > threshold:
                    character_command = "right"
                elif acc_x < -threshold:
                    character_command = "left"
                if acc_y > threshold:
                    character_command = "up"
                elif acc_y < -threshold:
                    character_command = "down"

                if character_command != last_character_command:
                    commands.append(character_command)
                    last_character_command = character_command

                    # 显示当前移动状态
                    if character_command == 'right':
                        display.draw_string(0, 50, "move:right", color=st7789.GREEN, bg=st7789.BLACK, size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
                    elif character_command == 'left':
                        display.draw_string(0, 50, "move:left ", color=st7789.GREEN, bg=st7789.BLACK, size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
                    elif character_command == 'up':
                        display.draw_string(0, 50, "move:up   ", color=st7789.GREEN, bg=st7789.BLACK, size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
                    elif character_command == 'down':
                        display.draw_string(0, 50, "move:down ", color=st7789.GREEN, bg=st7789.BLACK, size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)

            # 读取摇杆和按键数据
            joystick_data = joystick.read()
            A_button, B_button, C_button, D_button, X_axis, Y_axis = joystick_data

            if X_axis != 0 or Y_axis != 0:
                mouse_move_command = "mouse_move," + str(X_axis * 50) + "," + str(-Y_axis * 50)
                commands.append(mouse_move_command)

            if D_button == 0:
                if not mouse_left_down:
                    commands.append("mouse_left_down")
                    mouse_left_down = True
            elif D_button == 1 and mouse_left_down:
                commands.append("mouse_left_up")
                mouse_left_down = False

            if B_button == 0:
                commands.append("mouse_right_click")
            if A_button == 0:
                commands.append("mouse_middle_click")
            if C_button == 0 and not mode_switch_pending:
                commands.append("switch_mode")
                mode_switch_pending = True
                current_mode = "fire" if current_mode == "water" else "water"
            elif C_button == 1:
                mode_switch_pending = False

            if commands:
                character_command_str = "character:" + ",".join(filter(lambda x: "mouse" not in x, commands))
                mouse_command_str = "mouse:" + ",".join(filter(lambda x: "mouse" in x, commands))

                if character_command_str != "character:":
                    s.send(character_command_str + "\n")  # 发送人物移动数据
                    print("发送人物数据:", character_command_str)

                if mouse_command_str != "mouse:":
                    s.send(mouse_command_str + "\n")  # 发送鼠标移动数据
                    print("发送鼠标数据:", mouse_command_str)

            utime.sleep(0.01) 
    finally:
        s.close()
        print("连接已关闭")

except OSError as e:
    print('连接失败，无法连接到电脑:', e)
